//
//  CourseVideoListViewController.m
//  xpkc
//
//  Created by TopSageOSX on 14-8-25.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "CourseVideoListViewController.h"

@interface CourseVideoListViewController ()

@end

@implementation CourseVideoListViewController{
    //列表的视图
    UITableView *listTableView;
    //视图数据
    NSMutableArray *listArray;
    //头
    CourseListHeaderView *headerView;
    /**
     *  标题的内容
     */
    NSString *courseName;
    NSString *lastStudy;
    NSString *lectures;
    NSString *progress;
    NSString *teacherName;
    //下载标记
    BOOL downloadFlag;
    BottomView *bottomView;
    /**
     *  下载数组
     */
    NSMutableArray *downloadArray;
    //底部视图的高度
    int bottomH;
    //全选标记
    BOOL selectAllFlag;
    //存在标签
    NSInteger hadFlag;
    //临时数组，存放未下载的数据
    NSMutableArray *tempArray;
    //标记已有或其他状态数组
    NSMutableIndexSet *ingIndexSet;
    NSMutableIndexSet *hadIndexSet;
    NSMutableArray *hadArray;
    NSMutableArray *ingArray;
    NSMutableArray *hadindex;
    //标记完成的数组
    NSMutableArray *MyHadArray;
    RefreshView *refreshView;
    int list[128];
    int open;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.navigationItem.title=@"章节列表";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    //初始化
    downloadArray = [[NSMutableArray alloc]init];
    for (int i = 0; i<128; i++) {
        list[i] = 0;
    }
    //创建导航栏
    [self creatNaviItem];
    //创建列表
    [self creatListView];
    [self creatTopView];
    //创建底部视图
    [self creatBottomView];
    refreshView  = [[RefreshView alloc]init];
    [self.view bringSubviewToFront:refreshView];
    [self.view addSubview:refreshView];
    //获取信息
    [self getClassInfo];
    
    
}
/**
 *  获取课程的视频列表
 *
 */
-(void)getClassInfo{
    [refreshView startRefresh];
    NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
    NSString *string = [NSString stringWithFormat:@"/CourseCenter/lectureList/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
    NSString *MD5string = [string md5];
    NSString *urlString = [NSString stringWithFormat:@"http://www.studypay.com/MAPI/index.php/CourseCenter/lectureList/hash/%@/appid/1", MD5string];
    logdebug(@"%@",self.classId);
    NSDictionary *paramters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",self.mid,@"mid",self.classId,@"class_id", nil];
    //请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:paramters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //成功
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //解析
        NSArray *videoListArray = [dic objectForKey:@"LectureList"];
        listArray = [[NSMutableArray alloc]init];
        logdebug(@"==%@",dic);
        courseName = [dic objectForKey:@"courseName"];
        lastStudy = [NSString stringWithFormat:@"%@",[dic objectForKey:@"lastStudy"]];
        lectures = [NSString stringWithFormat:@"%@",[dic objectForKey:@"lectures"]];
        progress = [NSString stringWithFormat:@"%@",[dic objectForKey:@"progress"]];
        teacherName = [dic objectForKey:@"teacher"];
        for (NSDictionary *videoDic in videoListArray) {
            VideoListModel *videoModel = [[VideoListModel alloc]init];
            videoModel.duration = [videoDic objectForKey:@"duration"];
            videoModel.videoId = [videoDic objectForKey:@"id"];
            videoModel.chapter = [videoDic objectForKey:@"lecture_chapter"];
            videoModel.section = [videoDic objectForKey:@"lecture_section"];
            videoModel.spark = [videoDic objectForKey:@"spark"];
            videoModel.drm = [videoDic objectForKey:@"drm"];
            videoModel.teacher = [videoDic objectForKey:@"teacher"]!=[NSNull null]?[videoDic objectForKey:@"teacher"]:@"";
            videoModel.spark = [videoDic objectForKey:@"spark"];
            videoModel.drm = [videoDic objectForKey:@"drm"];
            videoModel.lecture = [dic objectForKey:@"courseName"];
            videoModel.hadlocal = NO;
            BOOL hadmo = NO;
            NSMutableDictionary *dictinary;
            for (int i = 0; i<listArray.count; i++) {
                dictinary = [NSMutableDictionary dictionaryWithDictionary:[listArray objectAtIndex:i]];
                NSMutableArray *marray = [NSMutableArray arrayWithArray:[dictinary objectForKey:@"array"]];
                if ([[dictinary objectForKey:@"chapter"]isEqualToString:videoModel.chapter]) {
                    //
                    hadmo = YES;
                    logdebug(@"已有分组%@",videoModel.chapter);
                }
                if (hadmo) {
                    [marray addObject:videoModel];
                    [dictinary setObject:marray forKey:@"array"];
                    [listArray replaceObjectAtIndex:i withObject:dictinary];
                    //                    list[i] = marray.count;
                    if ([lastStudy isEqualToString:videoModel.videoId]) {
                        open = i;
                    }
                    i = listArray.count+1;//用于跳出的玩意
                    
                }
            }
            if (!hadmo) {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:videoModel];
                dictinary = [NSMutableDictionary dictionaryWithObjectsAndKeys:videoModel.chapter,@"chapter",array,@"array", nil];
                [listArray addObject:dictinary];
                if ([lastStudy isEqualToString:videoModel.videoId]) {
                    open = listArray.count-1;
                }
            }
        }
        //保存暂存数组，用于展开收放等的数据
        tempArray = [NSMutableArray arrayWithArray:listArray];
        if (listArray.count==0) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"课程制作中..." delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        
        //刷新视图
        [self checkHaddown];
        [listTableView reloadData];
        [refreshView endRefresh];
        [self creatTopView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //失败
        logdebug(@"%@",error.localizedDescription);
    }];
}
/**
 *  获取视频课程的详细信息（用于记录最后学习进度）
 *
 */
-(void)getVideoInfoToLastStudy:(VideoListModel*)model{
    NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
    NSString *string = [NSString stringWithFormat:@"/CourseCenter/videoDisplay/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
    NSString *MD5string = [string md5];
    NSString *urlString = [NSString stringWithFormat:@"http://www.studypay.com/MAPI/index.php/CourseCenter/videoDisplay/hash/%@/appid/1", MD5string];
    
    NSDictionary *paramters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",self.mid,@"mid",model.videoId,@"lectureId", nil];
    //请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:paramters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //成功
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //失败
        logdebug(@"%@",error.localizedDescription);
    }];
}

#pragma mark - 视图创建等
/**
 *  创建列表视图
 *
 */
-(void)creatListView{
    listTableView = [[UITableView alloc]init];
    listTableView.frame = RECT(0, 80, SCREEN_WIDTH, SCREEN_HEIGHT-64-80);
    listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    listTableView.delegate = self;
    listTableView.dataSource = self;
    listTableView.tintColor = UIColorFromRGB(0x00ad58);
    [self.view addSubview:listTableView];
}
/**
 *  创建标题栏
 */
-(void)creatNaviItem{
    UIImage *image = [UIImage imageNamed:@"back1"];
    if (IsIOS7) {
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStyleBordered target:self action:@selector(backtocourse)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    UIBarButtonItem *downItem = [[UIBarButtonItem alloc]initWithTitle:@"下载" style:UIBarButtonItemStyleBordered target:self action:@selector(downloadVideos)];
    [downItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:16.0], NSFontAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = downItem;
}
/**
 *  返回上一层
 */
-(void)backtocourse{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  创建顶部视图
 */
- (void)creatTopView{
    headerView = [[CourseListHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
    headerView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
    [self setTopViewValue];
    [self.view addSubview:headerView];
    
}
/**
 *  顶部视图赋值
 */
- (void)setTopViewValue{
    //保证完成数据下载再赋值
    if (listArray.count>0) {
        headerView.titleLabel.text = courseName;
        headerView.teacherLabel.text = teacherName;
        float num=[progress floatValue];
        int num1=num*lectures.floatValue;
        NSString *str=[NSString stringWithFormat:@"%d/%@",num1,lectures];
        headerView.progressView.frame = CGRectMake(0, 0, 80*num, headerView.progressView.bounds.size.height);
        headerView.progressLabel.text = str;
        headerView.lecturesLabel.text = lectures;
        [headerView.lastBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        [headerView.lastStudyBtn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
        [headerView.collectBtn addTarget:self action:@selector(onlyCollectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}
/**
 *  创建底部视图
 */
-(void)creatBottomView{
    bottomView = [[BottomView alloc]init];
    if (isPad) {
        bottomH = 49+49+64;
    }else{
        bottomH = 49+25+64;
    }
    bottomView.frame = RECT(0, SCREEN_HEIGHT-bottomH, SCREEN_WIDTH, bottomH);
    [bottomView.leftBtn setTitle:@"全选" forState:UIControlStateNormal];
    [bottomView.rightBtn setTitle:@"开始下载" forState:UIControlStateNormal];
    [bottomView.leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bottomView.leftBtn addTarget:self action:@selector(selectAllVideos:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView.rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bottomView.rightBtn addTarget:self action:@selector(startDownload:) forControlEvents:UIControlEventTouchUpInside];
    [self.view bringSubviewToFront:bottomView];
    [self.view addSubview:bottomView];
    bottomView.hidden = YES;
    
}

#pragma mark - tableview相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return listArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *dic = [listArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:@"array"];
    //    return array.count;
    if (section == open) {
        list[section] = array.count;
        return array.count;
    }else{
        return list[section];
    }
    //    return list[section];
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    CourseListCellHeaderView *header = [[CourseListCellHeaderView alloc]init];
    NSDictionary *dict = [listArray objectAtIndex:section];
    header.chapter.text = [dict objectForKey:@"chapter"];
    header.headBtn.tag = section;
    if (list[section]==0) {
        //
        [header close:YES];
    }else{
        [header close:NO];
    }
    [header.headBtn addTarget:self action:@selector(headshow:) forControlEvents:UIControlEventTouchUpInside];
    if (downloadFlag) {
        [header move:1];
    }else{
        [header move:2];
    }
    if (downloadFlag) {
        header.userInteractionEnabled = NO;
    }else{
        header.userInteractionEnabled = YES;
    }
    logdebug(@"头部视图");
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (isPad) {
        return 60;
    }else{
        return 40;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (isPad) {
        return 80;
    }else{
        return 60;
    }
}
//课程列表
-(CourseListCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CourseListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[CourseListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    //    if (downloadFlag) {
    //        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    //    }else{
    //        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //    }
    NSDictionary *dict = [listArray objectAtIndex:indexPath.section];
    NSArray *array = [dict objectForKey:@"array"];
    VideoListModel *model = [array objectAtIndex:indexPath.row];
    cell.lectureChapter.text = model.section;
    cell.teacher.text = model.teacher;
    cell.duration.text = [NSString stringWithFormat:@"%@分",model.duration];

    //最后不到底
    if (indexPath.row+1 == array.count) {
        if (isPad) {
            cell.line.frame = CGRectMake(20, 0, 1, 25);
        }else{
            cell.line.frame = CGRectMake(20, 0, 1, 20);
        }
    }else{
        if (isPad) {
            cell.line.frame = CGRectMake(20, 0, 1, 80);
        }else{
            cell.line.frame = CGRectMake(20, 0, 1, 60);
        }
    }
    //检查下载否
    BOOL hadoring = NO;
    for (VideoListModel *mod in hadArray) {
        if ( [mod.spark isEqualToString: model.spark]) {
            cell.downState.text = @"已下载";
            logdebug(@"%@已经下载",model.spark);
            cell.downState.textColor = GreenColor;
            hadoring = YES;
            model.hadlocal = YES;//标明已下载
        }
    }
    for (VideoListModel *mod in ingArray) {
        if ([mod.spark isEqualToString: model.spark]) {
            cell.downState.text = @"下载中";
            logdebug(@"%@下载中",model.spark);
            cell.downState.textColor = [UIColor orangeColor];
            hadoring = YES;
        }
    }
    if (!hadoring) {
        cell.downState.textColor = [UIColor lightGrayColor];
        cell.downState.text = @"未下载";
    }
    NSArray *favorites = [NSArray arrayWithContentsOfFile:FAVORITE_PATH];
    BOOL fav = NO;
    for (NSString *spark in favorites) {
        if ([spark isEqualToString:model.spark]) {
            fav = YES;
        }
    }
    cell.isFavorite = fav;
    //FIXME:最新判断需要新的数据支持，暂时只显示为最后更新的
    if (indexPath.section == listArray.count-1) {
        cell.isNew = YES;
    }else{
        cell.isNew = NO;
    }
    
    cell.stateBtn.backgroundColor = [UIColor clearColor];
    cell.stateBtn.tag=indexPath.section*100 + indexPath.row;
    [cell.stateBtn addTarget:self action:@selector(playVideo:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
/**
 *  播放按钮
 *
 *  @param btn 按钮
 */
- (void)playVideo:(UIButton *)btn{
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:btn.tag%100 inSection:btn.tag/100];
    logdebug(@"播放%@",indexpath);
    if (![MyHadArray containsObject:indexpath]) {
        //未下载的
        logdebug(@"在线播放");
        if ([[[NSUserDefaults standardUserDefaults]valueForKey:WIFI_ONLY]isEqualToString:@"NO"]) {
            //随便看
            [self gotoMediaPlayer:indexpath];
        }else{
            //先判断网络状况
            if (![[GetNetworkStatues getNetWorkStates]isEqualToString:@"WIFI"])
            {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"当前处于非WIFI网络下,观看视频会产生大量流量，是否确认观看" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定观看", nil];
                alert.tag = btn.tag;
                [alert show];
            }else{
                [self gotoMediaPlayer:indexpath];
            }
        }
    }else{
        logdebug(@"本地播放");
        //本地播放
        NSDictionary *dict = [listArray objectAtIndex:indexpath.section];
        NSArray *array = [dict objectForKey:@"array"];
        VideoListModel *model = [array objectAtIndex:indexpath.row];
        
        NSString *spark = model.spark;
        NSString *drm = model.drm;
        DWCustomPlayerViewController *player = [[DWCustomPlayerViewController alloc]init];
        if ([drm isEqualToString:@"1"]) {
            //
            player.drm = YES;
            player.videoLocalPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,spark,@"pcm"];
        }else{
            player.drm = NO;
            player.videoLocalPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,spark,@"mp4"];
            
        }
        player.tem = 2;
        player.index = indexpath;
        player.nextArray = listArray;
        player.videoName = [NSString stringWithFormat:@"%@ %@",model.chapter,model.section];
        player.hidesBottomBarWhenPushed = YES;
        player.playerReturn = ^(NSInteger num){
            logdebug(@"返回完成");
        };
        [self getVideoInfoToLastStudy:model];
        DWCustomPlayerNavViewController *navVC = [[DWCustomPlayerNavViewController alloc]initWithRootViewController:player];
        [self presentViewController:navVC animated:YES completion:nil];
    }
}
/**
 *  展开
 */
//TODO:展开
- (void)headshow:(UIButton *)btn{
    if (open == btn.tag) {
        open = 1000;
    }
    if (list[btn.tag]>0) {
        logdebug(@"关闭");
        list[btn.tag] = 0;
        [listTableView reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }else{
        NSDictionary *dic = [listArray objectAtIndex:btn.tag];
        NSArray *array = [dic objectForKey:@"array"];
        list[btn.tag] = array.count;
        logdebug(@"开启");
        [listTableView reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
//点击选中某课
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //下载多选的时候
    if (downloadFlag) {
        NSDictionary *dict = [listArray objectAtIndex:indexPath.section];
        NSArray *array = [dict objectForKey:@"array"];
        VideoListModel *model = [array objectAtIndex:indexPath.row];
        [downloadArray addObject:model];
        return;
    }
    //TODO:新的选择方式获取信息
    if (![MyHadArray containsObject:indexPath]) {
        //未下载的
        logdebug(@"在线播放");
        if ([[[NSUserDefaults standardUserDefaults]valueForKey:WIFI_ONLY]isEqualToString:@"NO"]) {
            //随便看
            [self gotoMediaPlayer:indexPath];
        }else{
            //先判断网络状况
            if (![[GetNetworkStatues getNetWorkStates]isEqualToString:@"WIFI"])
            {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"当前处于非WIFI网络下,观看视频会产生大量流量，是否确认观看" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定观看", nil];
                alert.tag = 100;
                [alert show];
            }else{
                [self gotoMediaPlayer:indexPath];
            }
        }
    }else{
        logdebug(@"本地播放");
        //本地播放
        NSDictionary *dict = [listArray objectAtIndex:indexPath.section];
        NSArray *array = [dict objectForKey:@"array"];
        VideoListModel *model = [array objectAtIndex:indexPath.row];
        NSString *spark = model.spark;
        NSString *drm = model.drm;
        DWCustomPlayerViewController *player = [[DWCustomPlayerViewController alloc]init];
        if ([drm isEqualToString:@"1"]) {
            //
            player.drm = YES;
            player.videoLocalPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,spark,@"pcm"];
        }else{
            player.drm = NO;
            player.videoLocalPath = [NSString stringWithFormat:@"%@/%@.%@",DOC_PATH,spark,@"mp4"];
            
        }
        NSString *str = model.lecture;
        logdebug(@"%@",str);
        NSArray *array2 = [str componentsSeparatedByString:@" "];
        NSString *str2 = [array2 objectAtIndex:array2.count-1];
        
        player.videoName = [NSString stringWithFormat:@"%@ %@ %@",str2,model.chapter,model.section];
        //        player.videoName = [NSString stringWithFormat:@"%@ %@",model.chapter,model.section];
        player.hidesBottomBarWhenPushed = YES;
        player.tem = 2;
        player.index = indexPath;
        player.nowVideo = indexPath.row;
        player.nextArray = listArray;
        player.playerReturn = ^(NSInteger num){
            logdebug(@"完成播放");
            [listTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        };
        [self getVideoInfoToLastStudy:model];
        DWCustomPlayerNavViewController *navVC = [[DWCustomPlayerNavViewController alloc]initWithRootViewController:player];
        [self presentViewController:navVC animated:YES completion:nil];
    }
}
//取消选择
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    //撤销下载的选项
    NSDictionary *dict = [listArray objectAtIndex:indexPath.section];
    NSArray *aray = [dict objectForKey:@"array"];
    ListenTestModel *model = [aray objectAtIndex:indexPath.row];
    [downloadArray removeObject:model];
}
//编辑样式
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    logdebug(@"改变cell的编辑样式");
    if (downloadFlag) {
        if ([hadindex containsObject:indexPath]) {
            //FIXEME:等待适配新的数据
            //判断是否已在下载列表
            //存在的就没有编辑样式
            return UITableViewCellEditingStyleNone;
        }else{
            return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
        }
    }else{
        return UITableViewCellEditingStyleNone;
    }
}
//刷新用
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
}
#pragma mark - 下载相关
/***********************************
 *  批量下载方法
 */
-(void)downloadVideos{
    if (downloadFlag) {
        //取消下载
        headerView.collectBtn.userInteractionEnabled = YES;
        headerView.lastStudyBtn.userInteractionEnabled = YES;
        downloadFlag = NO;
        for (int i = 0; i<listArray.count; i++) {
            [listTableView reloadSections:[NSIndexSet indexSetWithIndex:i] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        [listTableView reloadData];
        //恢复之前去掉的已下载的
        [downloadArray removeAllObjects];
        [listTableView setEditing:NO animated:YES];
        self.navigationItem.rightBarButtonItem.title = @"下载";
        self.navigationItem.leftBarButtonItem.customView.hidden = NO;
        bottomView.hidden = NO;
        [bottomView hideAnimationWithTime:0.8 andDely:0.0];
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.8];
        listTableView.frame = RECT(0, 80, SCREEN_WIDTH, SCREEN_HEIGHT-64-80);
        [UIView commitAnimations];
        [bottomView hideColor];
        bottomView.hidden = YES;
        headerView.lastStudyBtn.userInteractionEnabled = YES;
    }else{
        downloadFlag = YES;
        //禁用防操作
        headerView.collectBtn.userInteractionEnabled = NO;
        headerView.lastStudyBtn.userInteractionEnabled = NO;
        for (int i = 0; i<listArray.count; i++) {
            NSDictionary *dict = [listArray objectAtIndex:i];
            NSArray *array = [dict objectForKey:@"array"];
            list[i] = array.count;
            [listTableView reloadSections:[NSIndexSet indexSetWithIndex:i] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        //进入下载
        bottomView.hidden = NO;
        //去掉数组中已经下载或下载中的
        [downloadArray removeAllObjects];
        //检查一遍再
        [self checkHaddown];
        [listTableView setEditing:YES animated:YES];
        self.navigationItem.rightBarButtonItem.title = @"取消";
        self.navigationItem.leftBarButtonItem.customView.hidden = YES;
        [bottomView showAnimationWithTime:0.8 andDely:0.0];
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.8];
        listTableView.frame = RECT(0, 80, SCREEN_WIDTH, SCREEN_HEIGHT-bottomH-80);
        //底部动画和属性
        [UIView commitAnimations];
        NSFileManager *manager =
        [NSFileManager defaultManager];
        NSDictionary * infoDic =
        [manager fileSystemAttributesAtPath:NSHomeDirectory()];
        float usedsize = [[infoDic objectForKey:@"NSFileSystemSize"]integerValue]/1024.0/1024.0-[[infoDic objectForKey:@"NSFileSystemFreeSize"]integerValue]/1024.0/1024.0;
        float mediasize = [GetFileSize folderSizeAtPath:DOC_PATH];
        logdebug(@"视频大小%f",mediasize);
        float freesize = [[infoDic objectForKey:@"NSFileSystemFreeSize"]integerValue]/1024.0/1024.0;
        [bottomView setColorWith:usedsize andMedia:mediasize andFree:freesize];
        bottomView.noteLabel.text = [NSString stringWithFormat:@"已用:%0.1fG(学派视频:%0.1fM)/空闲:%0.1fG",usedsize/1024.0,mediasize,freesize/1024.0];
        bottomView.noteLabel.font = FONT_SYS_NORMAL;
        headerView.lastStudyBtn.userInteractionEnabled = NO;
        
    }
}
/**
 *  开始批量下载
 */
-(void)startDownload:(UIButton *)btn{
    //遍历数组添加到下载
    for (int i = 0; i<downloadArray.count; i++) {
        VideoListModel *model = [downloadArray objectAtIndex:i];
        NSString *drm = [model.drm copy];
        NSString *videoId = [model.videoId copy];
        NSString *lecture_chapter = [model.chapter copy];
        NSString *lecture_section = [model.section copy];
        NSString *spark = [model.spark copy];
        NSString *teacher = [model.teacher copy];
        NSString *lecture = [model.lecture copy];
        NSString *duration = [model.duration copy];
        NSString *lectureNum = [NSString stringWithFormat:@"%@",lectures];
        NSString *usermid = [[UserMessage sharedUserMessage].userMid copy];
        NSDictionary *downDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                 drm,@"drm",
                                 spark,@"spark",
                                 videoId,@"videoId",
                                 lecture_chapter,@"chapter",
                                 lecture_section,@"section",
                                 teacher,@"teacher",
                                 duration,@"duration",
                                 lecture,@"lecture",
                                 lectureNum,@"lectureNum",
                                 usermid,@"usermid",
                                 nil];
        [[NSNotificationCenter defaultCenter]postNotificationName:START_DOWNLOAD_NOTIFICATION object:nil userInfo:downDic];
    }
    if (downloadArray.count==0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"您未选择要下载的课程" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
    }else{
        //提示
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"已成功添加到下载列表" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        //关闭视图
        [self downloadVideos];
    }
}

/**
 *  全选
 *
 *  @param btn btn
 */
-(void)selectAllVideos:(UIButton *)btn{
    if (selectAllFlag) {
        selectAllFlag = NO;
        for (int i = 0; i<listArray.count; i++) {
            NSDictionary *dict = [listArray objectAtIndex:i];
            NSArray *array = [dict objectForKey:@"array"];
            for (int j = 0; j<array.count; j++) {
                [listTableView deselectRowAtIndexPath:[NSIndexPath indexPathForItem:j inSection:i] animated:YES];
            }
        }
        [downloadArray removeAllObjects];
        [bottomView.leftBtn setTitle:@"全选" forState:UIControlStateNormal];
    }else{
        selectAllFlag = YES;
        for (int i = 0; i<listArray.count; i++) {
            NSDictionary *dict = [listArray objectAtIndex:i];
            NSArray *array = [dict objectForKey:@"array"];
            for (int j = 0; j<array.count; j++) {
                VideoListModel *model = [array objectAtIndex:j];
                [downloadArray addObject:model];
                for (NSIndexPath *index in hadindex) {
                    logdebug(@"检查中是否下载");
                    if (index.section==i&&index.row == j) {
                        //不添加
                        logdebug(@"已在下载");
                        [downloadArray removeLastObject];
                        break;
                    }
                    
                }
            }
        }
        for (int i = 0; i<listArray.count; i++) {
            NSDictionary *dict = [listArray objectAtIndex:i];
            NSArray *array = [dict objectForKey:@"array"];
            for (int j = 0; j<array.count; j++) {
                [listTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:j inSection:i] animated:YES scrollPosition:UITableViewScrollPositionNone];
            }
        }
        [bottomView.leftBtn setTitle:@"取消全选" forState:UIControlStateNormal];
    }
}
//继续学习
-(void)btnClick{
    NSString *spark;
    NSIndexPath *index;
    for (int i = 0; i<listArray.count; i++) {
        NSDictionary *dict = [listArray objectAtIndex:i];
        NSArray *array = [dict objectForKey:@"array"];
        for (int j = 0; j<array.count; j++) {
            VideoListModel *model = [array objectAtIndex:j];
            if ([model.videoId isEqualToString:lastStudy]) {
                //
                spark = [model.spark copy];
                index = [NSIndexPath indexPathForItem:j inSection:i];
                //跳出用的
                j = array.count;
                i = listArray.count;
                break;
            }
        }
    }
    [self gotoMediaPlayer:index];
}
/**
 *  检查
 */
-(void)checkHaddown{
    logdebug(@"检查");
    hadFlag = 0;
    //遍历本地查找是否存在了
    //完成字典
    NSDictionary *downingdic = [NSDictionary dictionaryWithContentsOfFile:DOWNLOADING_PATH];
    NSArray *downingArray = [downingdic objectForKey:@"videos"];
    //下载中字典
    NSDictionary *downeddic = [NSDictionary dictionaryWithContentsOfFile:DOWNLOADED_PATH];
    NSArray *downedArray = [downeddic objectForKey:@"videos"];
    hadArray = [NSMutableArray array];
    ingArray = [NSMutableArray array];
    hadindex = [NSMutableArray array];
    MyHadArray = [NSMutableArray array];
    [hadArray removeAllObjects];
    [ingArray removeAllObjects];
    [hadindex removeAllObjects];
    [MyHadArray removeAllObjects];
    //先查完成的
    for (int i = 0; i<listArray.count; i++) {
        NSDictionary *dict = [listArray objectAtIndex:i];
        NSArray *array = [dict objectForKey:@"array"];
        for (int j = 0; j<array.count; j++) {
            VideoListModel *model = [array objectAtIndex:j];
            for (NSDictionary *downedDic in downedArray) {
                NSArray *darray = [downedDic objectForKey:@"array"];
                for (NSDictionary *ddic in darray) {
                    if ([[ddic objectForKey:@"videoId"]isEqualToString:model.spark]) {
                        hadFlag = 2;
                        //下载完成有
                        logdebug(@"%@已下载完成",model.spark);
                        [hadArray addObject:model];
                        [hadindex addObject:[NSIndexPath indexPathForItem:j inSection:i]];
                        [MyHadArray addObject:[NSIndexPath indexPathForItem:j inSection:i]];
                        break;
                    }
                }
                if ([[downedDic objectForKey:@"videoId"]isEqualToString:model.spark]) {
                    hadFlag = 2;
                    //下载完成有
                    logdebug(@"%@已下载完成",model.spark);
                    [hadArray addObject:model];
                    [hadindex addObject:[NSIndexPath indexPathForItem:j inSection:i]];
                    [MyHadArray addObject:[NSIndexPath indexPathForItem:j inSection:i]];
                    break;
                }
            }
            for (NSDictionary *downingDic in downingArray) {
                if ([[downingDic objectForKey:@"videoId"]isEqualToString:model.spark]) {
                    hadFlag = 1;
                    //下载中
                    logdebug(@"%@已下载中",model.spark);
                    [ingArray addObject:model];
                    [hadindex addObject:[NSIndexPath indexPathForItem:j inSection:i]];
                    break;
                }
            }
        }
    }
    logdebug(@"检查完毕");
    [listTableView reloadData];
}
/**
 *  前往视频界面
 */
-(void)gotoMediaPlayer:(NSIndexPath *)index{
    //获取新的数据
    NSDictionary *dict = [listArray objectAtIndex:index.section];
    NSArray *array = [dict objectForKey:@"array"];
    VideoListModel *model = [array objectAtIndex:index.row];
    NSString *spark = model.spark;
    NSString *drm = model.drm;
    DWCustomPlayerViewController *player = [[DWCustomPlayerViewController alloc]init];
    player.videoId = spark;
    if ([drm isEqualToString:@"1"]) {
        //
        player.drm = YES;
    }else{
        player.drm = NO;
    }
    player.videoName = [NSString stringWithFormat:@"%@ %@",model.chapter,model.section];
    player.nextArray = listArray;
    player.nowVideo = index.row;
    player.index = index;
    player.hidesBottomBarWhenPushed = YES;
    player.tem = 2;
    player.playerReturn= ^(NSInteger num){
        logdebug(@"返回视频位置%d",num);
        //更新这一个，检查是否加入了收藏
        [listTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index, nil] withRowAnimation:UITableViewRowAnimationNone];
    };
    [self getVideoInfoToLastStudy:model];
    DWCustomPlayerNavViewController *navVC = [[DWCustomPlayerNavViewController alloc]initWithRootViewController:player];
    [self presentViewController:navVC animated:YES completion:nil];
}
/**
 *  提示框代理
 *
 *  @param alertView   alertView
 *  @param buttonIndex buttonIndex
 */
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView.title isEqualToString:@"警告"]) {
        if (buttonIndex == 0) {
            //
            return;
        }else{
            [self gotoMediaPlayer:[NSIndexPath indexPathForItem:alertView.tag%100 inSection:alertView.tag/100]];
        }
    }
    if ([alertView.message isEqualToString:@"课程制作中..."]) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self checkHaddown];
    }
}
/**
 *   只显示收藏
 *
 */
-(void)onlyCollectBtnClick:(UIButton *)btn{
    //已在视图中做了改变
    if (btn.selected) {
        logdebug(@"只看收藏");
    }else{
        logdebug(@"显示全部");
    }
}
//**********************************
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
